var express = require('express');
var router = express.Router();
let {UserM} =require('../../modules/long')
let jwt = require('jsonwebtoken')
let md5 = require('md5-node');
let multiparty=require('multiparty')
let ws = require('ws')
//腾讯人脸识别包(npm i tencentcloud-sdk-nodejs-iai)
const tencentcloud = require("tencentcloud-sdk-nodejs-iai");

const wss = new ws.Server({port:8080},()=>{
  console.log('服务器连接成功');
})

wss.on('connection',function(socket){
  console.log('有客户端连接');
  socket.on('message',function(msg){
    console.log('客户端发来的信息',msg);
    // socket.send('服务器接收'+msg.toString())
      wss.clients.forEach(function(client){
      client.send('客户端已登录')
    })
  })
})

/*账户登录验证 */
router.post('/user', async(req, res)=>{
  let {name,pawd}=req.body
  let data =await UserM.find({username:name})
  let pawds =md5(pawd)
  if(data.length<=0){
    console.log(data);
    return res.send({
      code:404,
      msg:'用户不存在'
    })
  }
  if(data[0].pawdname!=pawds){
    return res.send({
      code:401,
      msg:'密码错误'
    })
  }
  let userInfo={
    name,
  }
  let accessToken = jwt.sign(userInfo,'abcdefg',{expiresIn:'3s'})
  let refreshToken= jwt.sign(userInfo,'abcdefg',{expiresIn:'7d'})
  console.log(data,3333);
  return res.send({
    code:200,
    data:{
      name,
      accessToken,
      refreshToken
    }
  })
});

// 刷新token
router.get('/refresh',async(req,res)=>{
  let token =req.query.token
  let name=''
  try{
    let userInfo = jwt.verify(token,'abcdefg')
    // console.log(userInfo);
    name = userInfo.name
  }catch(error){
    console.log('错误');
    res.send({
      code:414,
      msg:'token失效，请重新登录'
    })
  }
  let userInfo={
    name
  }
  let accessToken = jwt.sign(userInfo,'abcdefg',{expiresIn:'3s'})
  let refreshToken = jwt.sign(userInfo,'abcdefg',{expiresIn:'7d'})
  console.log('成功');
  res.send({
    code:200,
    data:{
      accessToken,
      refreshToken
    }
  })
})

router.get('/login',async(req,res)=>{
  let data=await UserM.find()
  res.send({
    code:200,
    data
  })
})



//人脸识别登录
router.post('/faceLogin',async (req, res) => {
    //获取前端传来的base64
    let b64 = req.body.b64
    
    const IaiClient = tencentcloud.iai.v20200303.Client;

    const clientConfig = {
        credential: {
            //自己的腾讯secretId
            secretId: "AKIDFNJ8mFWaN4GICuSowrY3NVR9g5KQLF0b",
            //自己的腾讯密匙
            secretKey: "Vr21pTRn14xgFeAWijZDi3CAxZ0EJWaX",
        },
        region: "ap-beijing",  //地域参数（华北地区北京）
        profile: {
            httpProfile: {
                endpoint: "iai.tencentcloudapi.com",
            },
        },
    };

    const client = new IaiClient(clientConfig);

    const params = {
        "GroupIds": [  //你创建的人员库ID
            "110"
        ],
        "Image": b64,  //图片的base64格式编码
        "NeedPersonInfo": 1,  //是否返回人员具体信息。0 为关闭，1 为开启。默认为 0。
        "QualityControl": 1,  //图片质量控制。 0: 不进行控制； 1:较低的质量要求
        "FaceMatchThreshold": 85,  //人脸对比度设置为大于85才可
    };

    let doc = await client.SearchFaces(params)
	
    //doc为人脸识别后的返回信息
    console.log(doc,'doc',doc.FaceNum,11111111111111111);

    if(doc.FaceNum==1){  //表示当前人脸库有该人员
        let personId = doc.Results[0].Candidates[0].PersonId  //拿到该人员的ID
        let personName = doc.Results[0].Candidates[0].PersonName  //拿到该人员的名称
        console.log(personName,'personNume');
        //根据该人员的名称去MongoDB中查询该用户对象(可以跳过这一步)
        let userObj = await UserM.findOne({username:personName})
        console.log(userObj,'userObj');
        if (userObj) {  //如果查询到该用户
            //生成token
            let name=userObj.username
            let userInfo={
              name,
            }
            console.log(userInfo);
            let accessToken = jwt.sign(userInfo,'abcdefg',{expiresIn:'3s'})
            let refreshToken= jwt.sign(userInfo,'abcdefg',{expiresIn:'7d'})
            console.log(accessToken,refreshToken);
            res.send({
                code: 200,
                msg: "登录成功！",
                data:{
                  accessToken,
                  refreshToken
                }
            })
            return false
        } else {
            res.send({
                code: 250,
                msg: "用户名或密码错误！",
                doc
            })
            return false
        }
    }else{
      console.log(222222222);
        res.send({
            code:251,
            msg:'人脸库无此人！'
        })
        return false
    }
})


//图片上传
router.post('/upload',async(req,res)=>{
  let from=new multiparty.Form()
  from.uploadDir='upload'
  console.log(req.body);
  from.parse(req,(err,fileter,files)=>{
      console.log(files.file);
      let path='http://127.0.0.1:3000/'+files.file[0].path
      console.log(path);
      res.send({
          code:200,
          path
      })
  })
})

module.exports = router;
